import React, { memo, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Tag, Toast } from "antd-mobile";
import { useDispatch } from "react-redux";
import store from "@/store";
import ListBlock from "@/components/ListBlock/ListBlock";
import { useHandleBeforeHome } from "@/router/routerBefore";
import { logout } from "@/store/modules/user";
import UserWrapper from "./style";
import UserInfoBox from "@/components/UserInfoBox";

const User = memo((props) => {
  useHandleBeforeHome();
  let navigate = useNavigate();
  let dispatch = useDispatch();

  let [user, setUser] = useState({});

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setUser(store.getState().user);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  let avatar = "";
  try {
    avatar = require(`../../components/img/${user.avatar}.png`);
  } catch (error) {
    // 如果图片出错，使用默认的头像
    avatar = require(`../../components/img/default.png`);
  }

  function handleLogout() {
    dispatch(logout());
    navigate("/login");
    Toast.show({
      content: "退出成功",
    });
  }
  return (
    <UserWrapper>
      <ListBlock>
        <img src={avatar} alt="" className="avatar" />
        <p className="username">{user.user}</p>
      </ListBlock>
      <ListBlock title="简介">
        <UserInfoBox user={user} />
      </ListBlock>
      <Button
        color="danger"
        className="btn"
        onClick={() => {
          handleLogout();
        }}
      >
        退出登录
      </Button>
    </UserWrapper>
  );
});

export default User;
